<?php

namespace App\Models\Member;

use App\Models\Common\City;
use App\Models\Common\Country;
use App\Models\Common\HandleLog;
use App\Models\Org;
use App\Models\School\Manager;
use App\Models\School\School;
use App\Models\Group\Group;
use App\Services\Com\LogService;
use App\Services\Geographical\Geographical;
use Emadadly\LaravelUuid\Uuids;
use Encore\Admin\Traits\DefaultDatetimeFormat;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;
use SMartins\PassportMultiauth\HasMultiAuthApiTokens;
use Spatie\Permission\Traits\HasRoles;
use App\Services\UrlCast;
use WeSoonNet\LaravelPlus\Traits\Timezone;

class Member extends Authenticatable
{
    use Notifiable, Uuids, HasRoles, HasMultiAuthApiTokens, Timezone, Geographical, DefaultDatetimeFormat, ModelTree;

    protected $table        = 'members';
    protected $guarded      = ['created_at', 'updated_at'];
//    public    $incrementing = false;
    protected $hidden       = ['pivot'];
    protected $casts        = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'deleted_at' => 'datetime:Y-m-d H:i:s',
//        'avatar_url' => UrlCast::class,
    ];

    protected static $kilometers = true;

    const LATITUDE = 'lat';
    const LONGITUDE = 'lng';

    public static function boot()
    {
        parent::boot();
    }


    /**
     * 自定义用户名验证规则
     *
     * @param $username
     *
     * @return mixed
     * @throws AuthenticationException
     */
    public function findForPassport($username)
    {
        // 字段
        $user  = $this->orWhere('mobile', $username)->first();

        if (!$user)
        {
            throw new AuthenticationException('用户不存在');
        }

        // 是否启用
        if (!$user->status)
        {
            throw new AuthenticationException('用户不可用');
        }

        return $user;
    }

    /**
     * 自定义密码验证规则
     *
     * @param $password
     *
     * @return bool
     * @throws AuthenticationException
     */
    public function validateForPassportPasswordGrant($password)
    {
        // 密码为 null 则跳过
        if ('__DONT_CHECK_PASSWORD__' === $password)
        {
            return true;
        }

        if (!Hash::check($password, $this->password))
        {
            throw new AuthenticationException('密码错误');
        }

        return true;
    }

    /**
     * 省
     */
    public function province()
    {
        return $this->belongsTo(City::class, 'province_id', 'id');
    }

    /**
     * 城市
     */
    public function city()
    {
        return $this->belongsTo(City::class, 'city_id', 'id');
    }

    public function org()
    {
        return $this->belongsTo(Org::class, 'org_id', 'id');
    }
}
